package com.liam.es.controller;


import com.alibaba.fastjson.JSONObject;
import com.liam.es.entity.mysql.MysqlBlog;
import com.liam.es.repository.mysql.MysqlBlogRepository;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RestController
public class DataController {
    @Autowired
    MysqlBlogRepository mysqlBlogRepository;

    @Autowired
    RestHighLevelClient elasticsearchClient;


    @GetMapping("/blogs")
    public Object blogs(){
        return mysqlBlogRepository.queryAll();
    }

    @GetMapping("/search")
    public Object search(String type,String keyword ){
        HashMap<String,Object> map = new HashMap<>();
        StopWatch watch = new StopWatch();
        watch.start();
        if("mysql".equals(type)){
            map.put("list",mysqlBlogRepository.queryBlogs(keyword));
        }else{

            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.from(0);
//            sourceBuilder.size(10);
//            sourceBuilder.fetchSource(new String[]{"name"}, new String[]{});
            MatchPhraseQueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery("name", keyword);
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            boolBuilder.should(matchQueryBuilder);
            sourceBuilder.query(boolBuilder);
            SearchRequest searchRequest = new SearchRequest("people");
            searchRequest.source(sourceBuilder);
            try {
                System.out.println(sourceBuilder.toString());
                SearchResponse response = elasticsearchClient.search(searchRequest,RequestOptions.DEFAULT);
                System.out.println(JSONObject.toJSONString(response.getHits().getHits()));
                map.put("list",response.getHits().getHits());
            } catch ( Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        watch.stop();
        map.put("duration",watch.getTotalTimeMillis());
        return map;
    }

}
